from web import models
from django.shortcuts import render, redirect
from django import forms
from utils.BootStrapForm import BootStrapForm
from utils.pager import Pagination
from django.urls import reverse
from utils.response import BaseResponse
from django.http import JsonResponse
from utils.link import filter_reverse


def policy_list(request):
    queryset = models.PricePolicy.objects.all()
    paginator = Pagination(request, queryset)
    return render(request, 'policy_list.html', {'paginator': paginator})


class PolicyModelForm(BootStrapForm, forms.ModelForm):
    class Meta:
        model = models.PricePolicy
        fields = '__all__'


def policy_add(request):
    if request.method == 'GET':
        form = PolicyModelForm()
        return render(request, 'form.html', {'form': form})

    form = PolicyModelForm(data=request.POST)
    if not form.is_valid():
        return render(request, 'form.html', {'form': form})

    form.save()
    return redirect(reverse('policy_list'))


def policy_edit(request, pk):
    instance = models.PricePolicy.objects.filter(id=pk).first()
    if request.method == 'GET':
        form = PolicyModelForm(instance=instance)
        return render(request, 'form.html', {'form': form})

    form = PolicyModelForm(data=request.POST, instance=instance)
    if not form.is_valid():
        return render(request, 'form.html', {'form': form})
    form.save()
    return redirect(filter_reverse(request, '/policy/list/'))
    # return redirect(reverse('policy_list'))


def policy_delete(request):
    cid = request.GET.get('cid', 0)
    if not cid:
        res = BaseResponse(status=False, detail="请选择要删除的数据!")
        return JsonResponse(res.dict)

    exists = models.PricePolicy.objects.filter(id=cid).exists()
    if not exists:
        res = BaseResponse(status=False, detail="数据不存在!")
        return JsonResponse(res.dict)

    models.PricePolicy.objects.filter(id=cid).delete()
    res = BaseResponse(status=True)
    return JsonResponse(res.dict)
